package com.shen.educenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.shen.commonutils.JwtUtils;
import com.shen.educenter.entity.UcenterMember;
import com.shen.educenter.service.UcenterMemberService;
import com.shen.educenter.utils.ConstantWxUtils;
import com.shen.educenter.utils.HttpClientUtils;
import com.shen.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Member;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/educenter/api/ucenter/wx")
public class WxApiController {

    @Autowired
    UcenterMemberService ucenterMemberService;
    @GetMapping("callback")
    //获取扫码人信息
    public  String callBack(String code,String state){
        //01 获取code--相当于手机验证码
        //02 根据token 请求微信固定地址--得到access_token 和openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);
        // 请求地址 得到access_token 和openid
        //使用httplient 发送请求--
        try{
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo----->"+accessTokenInfo);
            //从aceess_token 里面得到值-- 分割--
            //把acess_token 转换为map--使用gson --google 提供
            Gson gson=new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String)map.get("access_token");
            String openid = (String)map.get("openid");
            //拿着openid和access_token 得到用户信息

            //把扫码人信息添加到数据库里面
            //判断是否有相同的数据 openid

            UcenterMember member = ucenterMemberService.getByOpenId(openid);
            if(member==null){
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo--->"+userInfo);
                HashMap userInfoMapper = gson.fromJson(userInfo, HashMap.class);
                String nickname=(String) userInfoMapper.get("nickname");
                String headimgurl = (String)userInfoMapper.get("headimgurl");

                member=new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                boolean flag = ucenterMemberService.save(member);
                String jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());
                return "redirect:http://localhost:3000?token="+jwtToken;

            }
            else {
                String jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());
                return "redirect:http://localhost:3000?token="+jwtToken;
            }


        }
        catch (Exception e){
            throw new GuliException(20001,"failed--ucenter--callback");

        }


    //返回首页面
        //使用JWTt生成token

    }
    //1,生成二维码
    @GetMapping("login")
    public  String getVxCode() throws UnsupportedEncodingException {
    //固定地址 ，拼接参数---
//        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
//                "?appid="+ ConstantWxUtils.WX_OPEN_APP_ID +
//
//                "&redirect_uri="+ConstantWxUtils.WX_OPEN_REDIRECT_URL +
//
//                "&response_type=code";
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +

                "&redirect_uri=%s" +

                "&response_type=code" +

                "&scope=snsapi_login" +

                "&state=%s" +

                "#wechat_redirect";
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
       redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
//        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
//        System.out.println("state = " + state);
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");
        return "redirect:"+url;
    }


}
